package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.order.OrderFeign;
import com.atguigu.gmall.pay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付实现类
 * @author 搭忆长安
 * @version 1.0
 * @date 2021年07月14日 16:37
 * @ClassName:AliPayServiceImpl
 * @Description: TODO
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private OrderFeign orderFeign;
    @Value("${alipay_url}")
    private String alipay_url;

    @Value("${app_id}")
    private String app_id;

    @Value("${app_private_key}")
    private String app_private_key;

    @Value("${alipay_public_key}")
    private String alipay_public_key;

    @Value("${return_payment_url}")
    private String return_payment_url;

    @Value("${notify_payment_url}")
    private String notify_payment_url;

    /**
     * 支付宝下单
     * @param  map
     * @return
     */
    @Override
    public String aliPay(Map<String,String> map){
        //包装支付参数
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id,
                app_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        //声明请求体
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        try{
            //设置请求参数
            request.setReturnUrl(return_payment_url);
            request.setNotifyUrl(notify_payment_url);
            //封装BizContent
            Map<String,String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",map.get("orderId")+"");
            bizMap.put("product_code","FAST_INSTANT_TRADE_PAY");
            bizMap.put("total_amount",map.get("money"));
            bizMap.put("subject","java0107支付宝支付测试");
            Map<String,String> attchMap = new HashMap<>();
            attchMap.put("exchange",map.get("exchange"));
            attchMap.put("routingKey",map.get("routingKey"));
            //将附加参数进行转换为String类型
            String encode = URLEncoder.encode(JSONObject.toJSONString(attchMap), "utf-8");
            bizMap.put("passback_params",encode);
            request.setBizContent(JSONObject.toJSONString(bizMap));
            //发起请求
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            //解析结果
            if(response.isSuccess()){
                return  response.getBody();
            } else {
               return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }
    /**
     * 校验阿里支付的结果:主动查询
     * @param orderId
     * @return
     */
    @Override
    public String checkAluPay(Long orderId) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id,
                app_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        try{
            //封装BizContent
            Map<String,String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",orderId+"");
            request.setBizContent(JSONObject.toJSONString(bizMap));
            //发起请求
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            //解析结果
            if(response.isSuccess()){
                return  response.getBody();
            } else {
                return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }
    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @Override
    public String close(Long orderId) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id,
                app_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        try{
           // request.setBizContent(JSONObject.toJSONString(new HashMap<>().put("out_trade_no",orderId)));
            //封装BizContent
            Map<String,String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",orderId+"");
            request.setBizContent(JSONObject.toJSONString(bizMap));
            //发起请求
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            //解析结果
            if(response.isSuccess()){
                return  response.getBody();
            } else {
                return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }



    }
    /**
     * 退款
     * @param orderId
     * @return
     */
    @Override
    public String refund(Long orderId) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                app_id,
                app_private_key,
                "json",
                "utf-8",
                alipay_public_key,
                "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        try{
            // request.setBizContent(JSONObject.toJSONString(new HashMap<>().put("out_trade_no",orderId)));
            //封装BizContent
            Map<String,String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",orderId+"");
            bizMap.put("refund_amount","0.01");
            bizMap.put("refund_reason","你不知道的退款");
            request.setBizContent(JSONObject.toJSONString(bizMap));
            //发起请求
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            //解析结果
            if(response.isSuccess()){
                return  response.getBody();
            } else {
                return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }

    }
}
